//
//  UTSubscriptionViewController.swift
//  UniversalTool
//
//  Created by LGB on 2025/3/4.
//

import UIKit
import Reachability
import ProgressHUD

class UTSubscriptionViewController: UTBaseViewController {
    
    @IBOutlet weak var nonDiscountView: UIView!
    @IBOutlet weak var nonDiscountPriceLabel: UILabel!
    @IBOutlet weak var discountView: UIView!
    @IBOutlet weak var originalPriceLabel: UILabel!
    @IBOutlet weak var discountPriceLabel: UILabel!
    @IBOutlet weak var countdownLabel: UILabel!
    let reachability = try! Reachability()
    var countdownTimer: CountdownTimer?
    
    lazy var discountTime: Date? = {
        if let date = UserDefaults.standard.object(forKey: utDiscount) as? Date {
            return date
        }
        guard let date = Calendar.current.date(byAdding: .day, value: 7, to: Date.now) else {
            return nil
        }
        UserDefaults.standard.set(date, forKey: utDiscount)
        return date
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#000000", alpha: 0.3)
        let attributes: [NSAttributedString.Key: Any] = [
            .strikethroughStyle: NSUnderlineStyle.single.rawValue
        ]
        NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged(_:)), name: .reachabilityChanged, object: reachability)
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
        let attributedText = NSAttributedString(string: originalPriceLabel.text ?? "", attributes: attributes)
        originalPriceLabel.attributedText = attributedText
        if let discountTime = discountTime {
            let totalTime = discountTime.timeIntervalSince1970 - Date.now.timeIntervalSince1970
            self.countdownLabel.text = self.formatTime(totalTime)
            if totalTime > 0 {
                self.countdownTimer = CountdownTimer(totalTime: totalTime)
                self.countdownTimer!.start(countdownHandler: { remainingTime in
                    self.countdownLabel.text = self.formatTime(remainingTime)
                }, completion: {
                    self.nonDiscountView.isHidden = false
                    self.discountView.isHidden = true
                })
                return
            }
            self.nonDiscountView.isHidden = false
            self.discountView.isHidden = true
        }
    }
    
    deinit {
        if let countdownTimer = countdownTimer {
            countdownTimer.stop()
            self.countdownTimer = nil
        }
        reachability.stopNotifier()
        NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
    }
    
    @objc func networkStatusChanged(_ notification: Notification) {
        let reachability = notification.object as! Reachability
        if reachability.connection != .unavailable {
            if let bundleID = Bundle.main.bundleIdentifier {
                fetchSubscriptionPrice(buildId: bundleID)
            }
        }
    }
    
    func fetchSubscriptionPrice(buildId: String) {
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbserves/api/appdingyue/info"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
        
        let parameters: [String: Any] = ["packageName": buildId]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            if let error = error {
                print("Error: \(error)")
                return
            }
            
            guard let data = data else {
                print("No data received")
                return
            }
            
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let dict = json["data"] as? [String: Any], let price = dict["price"] as? String {
                    DispatchQueue.main.async {
                        self.nonDiscountPriceLabel.text = price
                        self.discountPriceLabel.text = price
                    }
                }
                
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
        
        task.resume()
    }
    
    func formatTime(_ timeInterval: TimeInterval) -> String {
        let totalSeconds = Int(timeInterval)
        let days = totalSeconds / (24 * 60 * 60)
        let remainingSecondsAfterDays = totalSeconds % (24 * 60 * 60)
        let hours = remainingSecondsAfterDays / (60 * 60)
        let remainingSecondsAfterHours = remainingSecondsAfterDays % (60 * 60)
        let minutes = remainingSecondsAfterHours / 60
        let seconds = remainingSecondsAfterHours % 60
        return String(format: "%d 天 %d 时 %d 分 %d 秒", days, hours, minutes, seconds)
    }
    
    func subscriptionBurialPoint() {
        guard let bundleID = Bundle.main.bundleIdentifier else { return }
        guard let udid = UIDevice.current.identifierForVendor?.uuidString else { return }
        let urlString = baseUrl + "/lbbmajiabao/api/maidian_dingyueye"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
        
        let parameters: [String: Any] = [
            "name": bundleID,
            "udid": udid,
        ]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error: \(error)")
                return
            }
            guard let data = data else {
                print("No data received")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let dict = json["data"] as? [String: Any], let price = dict["price"] as? String {
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
        task.resume()
    }
    
    @IBAction func dismiss(_ sender: UITapGestureRecognizer) {
        countdownTimer?.stop()
        countdownTimer = nil
        self.dismiss(animated: false)
    }
    
    
    @IBAction func goPay(_ sender: UIButton) {
        subscriptionBurialPoint()
        YSIAPManager.shared().requestProduct(KContinuityID)
    }
    
    @IBAction func goRestore(_ sender: UIButton) {
        subscriptionBurialPoint()
        YSIAPManager.shared().restore()
    }
    
    @IBAction func goUserAgreement(_ sender: UIButton) {
        let vc = UTWebViewController()
        vc.linkUrl = userProtocolLink
        self.present(vc, animated: true)
    }
    
    @IBAction func goPrivacyAgreement(_ sender: UIButton) {
        let vc = UTWebViewController()
        vc.linkUrl = privacyAgreementLink
        self.present(vc, animated: true)
    }
    
}
 
